package inits

import (
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"shop/common/config"
)

func InitNacos() {
	n := config.AppConf.Nacos
	clientConfig := constant.ClientConfig{
		NamespaceId:         n.Namespace, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}

	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      n.Host,
			ContextPath: "/nacos",
			Port:        uint64(n.Port),
			Scheme:      "http",
		},
	}
	configClient, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: n.DataId,
		Group:  n.Group})
	if err != nil {
		panic(fmt.Sprintf("配置信息读取失败: %s", err))
	}
	err1 := json.Unmarshal([]byte(content), &n)
	if err1 != nil {
		panic(fmt.Sprintf("解析转码失败: %s", err1))
	}
	fmt.Println("nacos init success")
}
